import 'package:flutter/material.dart';
import 'package:nil/nil.dart';

class HomeCockpitTabs extends StatefulWidget {
  final List<Map<String, String>> tabs;

  final List<Widget>? views;

  // 值变动后事件
  final ValueChanged<dynamic>? onChanged;

  const HomeCockpitTabs({
    super.key,
    required this.tabs,
    this.views,
    this.onChanged,
  });

  @override
  State<HomeCockpitTabs> createState() => _HomeCockpitTabsState();
}

class _HomeCockpitTabsState extends State<HomeCockpitTabs> with TickerProviderStateMixin {
  late AnimationController animationController;

  TabController? tabController;

  int _currentIndex = 0;
  int _prevIndex = -1;

  _setCurrentIndex(int index) {
    // change the index
    setState(() {
      _prevIndex = _currentIndex;
      _currentIndex = index;
    });
    _triggerAnimation();
  }


  _goToIndex(int index) {
    if (index != _currentIndex) {
      _setCurrentIndex(index);
      tabController?.animateTo(index);
    }
  }
  _triggerAnimation() {
    // reset the animation so it's ready to go
    animationController.reset();
    // run the animation!
    animationController.forward();
  }

  @override
  void initState() {
    super.initState();
    tabController = TabController(length: widget.tabs.length, vsync: this)
      ..addListener(() {
        if (tabController?.index.toDouble() == tabController?.animation?.value) {
          //赋值 并更新数据
          _currentIndex = tabController!.index;
        }
      });
    animationController = AnimationController(vsync: this, duration: const Duration(milliseconds: 200));
    animationController.value = 1.0;
    animationController.addListener(() {
      setState(() {});
    });
  }

  final GlobalKey _tabsParentKey = GlobalKey();

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.only(left: 0, right: 0, top: 10, bottom: 10),
      height: 32,
      child: Column(
        children: [
          AnimatedBuilder(
              animation: animationController,
              key: _tabsParentKey,
              builder: (context, child) {
                return TabBar(
                  labelStyle: const TextStyle(fontSize: 14),
                  indicatorSize: TabBarIndicatorSize.label,
                  indicator: const BoxDecoration(),
                  controller: tabController,
                  isScrollable: false,
                  labelPadding: const EdgeInsets.all(0),
                  tabs: widget.tabs.asMap().entries.map((entry) {
                    DecorationImage? imageOption = const DecorationImage(
                      fit: BoxFit.cover,
                      image: NetworkImage("https://meal.kmszzxt.cn/mp/images/bk.jpg"),
                    );

                    final double animationValue;
                    if (entry.key == _currentIndex) {
                      animationValue = animationController.value;
                    } else if (entry.key == _prevIndex) {
                      animationValue = 1 - animationController.value;
                    } else {
                      animationValue = 0;
                    }
                    return InkWell(
                      child: Container(
                        decoration: BoxDecoration.lerp(
                            BoxDecoration(
                              borderRadius: BorderRadius.circular(16),
                            ),
                            BoxDecoration(
                              borderRadius: BorderRadius.circular(16),
                              image: const DecorationImage(
                                fit: BoxFit.cover,
                                image: NetworkImage("https://meal.kmszzxt.cn/mp/images/bk.jpg"),
                              ),
                            ),
                            animationValue),
                        padding: const EdgeInsets.all(5),
                        child: Text(
                          entry.value['title']!,
                          maxLines: 1,
                          softWrap: false,
                          textAlign: TextAlign.center,
                          overflow: TextOverflow.visible,
                          style: TextStyle.lerp(
                              const TextStyle(
                                color: Colors.black54,
                              ),
                              const TextStyle(
                                color: Colors.white,
                              ),
                              animationValue),
                        ),
                      ),
                      onTap: () {
                        if (widget.onChanged != null) {
                          widget.onChanged!(entry);
                        }
                        _goToIndex(entry.key);
                      },
                    );
                  }).toList(),
                );
              }),
          widget.views != null && widget.views!.isNotEmpty
              ? Expanded(
                  child: TabBarView(
                    children: widget.views!,
                  ),
                )
              : const SizedBox(
                  height: 0,
                )
        ],
      ),
    );
  }
}
